//
//  XMUserDetailInfoViewController.m
//  XiaoMiao
//
//  Created by Jim huang on 2018/4/25.
//  Copyright © 2018年 smallyou. All rights reserved.
//

//controller
#import "XMUserDetailInfoViewController.h"
#import "XMTypeListViewController.h"

//view
#import "KTiltleAndInputTableViewCell.h"
#import "XMUserDetailInfoMultiSelectTableViewCell.h"
#import "XMRemarkTableViewCell.h"
#import "XMSurgeryDetailTableViewCell.h"
#import "XMTypeListModel.h"

#define NUMBERS @"0123456789"
@interface XMUserDetailInfoViewController ()<UITextFieldDelegate>

//下一步
@property (nonatomic,strong) UIButton * sureBtn;
//列表数据
@property (nonatomic,strong) NSArray  * ListData;
//头部标题
@property (nonatomic,strong) NSArray  * ListHeader;
//列表占位字
@property (nonatomic,strong) NSArray  * ListPlaceHolder;
//医美史
@property (nonatomic,strong) NSArray  * SurgeryDetailArr;
//数据源
@property (nonatomic,strong)XMUserDetailTagListModel * tagListModel;
//手机
@property (nonatomic,strong)UITextField * phoneTextField;
//年龄
@property (nonatomic,strong)UITextField * ageTextField;
//过敏药物
@property (nonatomic,strong)UITextField * medicinalTextField;
//过敏食物
@property (nonatomic,strong)UITextField * foodTextField;
//备注
@property (nonatomic,strong)UITextView * remarkTextView;


@end

@implementation XMUserDetailInfoViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    self.title = @"选填资料";
    
    //列表数据
    self.ListData = @[@[@"手机",@"年龄"],@[@"既往病史"],@[@"生理状况"],@[@"医美史"],@[@"药物",@"食物"],@[@"其他"]];
    //头部标题
    self.ListHeader = @[@"下列资料均为选填",@"既往病史",@"生理状况",@"医美史",@"过敏病史",@"其他"];
    
    //列表占位字
    self.ListPlaceHolder = @[@[@"请输入手机号码",@"请输入真实年龄 如1970"],@[@""],@[@""],@[@"请添加医美史"],@[@"请输入过敏药物",@"请输入过敏食物"],@[@"请输入其他备注"]];
    [self getTag];
}

-(void)setUI{
    
    self.tableView.refreshEnable = NO;
    self.tableView.loadmoreEnable = NO;
    self.tableView.showsVerticalScrollIndicator = NO;

    [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.height.equalTo(@50);
    }];
    
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.sureBtn.mas_top);
    }];
    
}

#pragma mark ----netWork
-(void)getTag{
    
    MJWeakSelf
    [KLProgressHUD showWaitingHUD];
    [AppNetwork album_V2GetUserDetailTagCompletion:^(BOOL success, XMUserDetailTagListModel *model, AppError *error) {
        [KLProgressHUD hideHUDWithAnimated:YES];
        if (success) {
            weakSelf.tagListModel = model;
            [weakSelf.tableView reloadData];
        }else{
            [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
        }
    }];
}

#pragma mark ----action----
-(void)sureAction{
    NSMutableArray * thridIdsArr = [NSMutableArray array];
    NSMutableArray * fourthIdsArr = [NSMutableArray array];
    NSMutableArray * fifthIdsArr = [NSMutableArray array];
    
    for (XMTypeListClassifyModel * thirdmodel in self.SurgeryDetailArr) {
        if (thirdmodel.isSelected) {
            [thridIdsArr addObject:thirdmodel.id];
        }
        
        for (XMTypeListClassifyModel * fourthModel in thirdmodel.cateViews) {
            if (fourthModel.isSelected) {
                [fourthIdsArr addObject:fourthModel.id];
            }
            
            
            for (XMTypeListClassifyModel * fifthModel in fourthModel.cateViews) {
                if (fifthModel.isSelected) {
                    [fifthIdsArr addObject:fifthModel.id];
                }
            }
        }
    }
    
    self.createModel.position = [thridIdsArr componentsJoinedByString:@","];
    self.createModel.project = [fourthIdsArr componentsJoinedByString:@","];
    self.createModel.material = [fifthIdsArr componentsJoinedByString:@","];
    
  
    
    NSMutableArray * physiologicalArr = [NSMutableArray array];
    
    for (XMUserDetailTagModel * physiologicalModel in self.tagListModel.physiologicalConditionView) {
        if (physiologicalModel.isSelected) {
            [physiologicalArr addObject:physiologicalModel.id];
        }
    }
    
    NSMutableArray * medicalHisArr = [NSMutableArray array];

    for (XMUserDetailTagModel * medicalModel in self.tagListModel.medicalHistoryView) {
        if (medicalModel.isSelected) {
            [medicalHisArr addObject:medicalModel.id];

        }
    }
    self.createModel.medicalHistory = [medicalHisArr componentsJoinedByString:@","];
    self.createModel.physiologicalCondition = [physiologicalArr componentsJoinedByString:@","];
    
    

    
    self.createModel.phone = self.phoneTextField.text;
    
    if (self.ageTextField.text.length != 0) {
        
        if (self.ageTextField.text.length !=4 || (![[self.ageTextField.text substringWithRange:NSMakeRange(0,2)] isEqualToString:@"19"]&&![[self.ageTextField.text substringWithRange:NSMakeRange(0,2)] isEqualToString:@"20"])) {
            [KLProgressHUD showErrorHUDWithMessage:@"请输入正确年份 如1970"];
            return;
        }
    }
    
    self.createModel.age = self.ageTextField.text;
    self.createModel.medicinal = self.medicinalTextField.text;
    self.createModel.food = self.foodTextField.text;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark ----tableView----

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.ListData.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray * listArr = self.ListData[section];
    return listArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 || indexPath.section == 4) {
        return 50;
    }else if(indexPath.section == 1 || indexPath.section == 2){
        return 120;
        
    }else if(indexPath.section == 3){
        
        if (self.SurgeryDetailArr || self.createModel.partyRemark.length > 0) {
            
            return 130;

        }else{
            return 50;

        }
        
    }else{
        return 100;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 38;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]init];
    view.backgroundColor = kBgColor;
    
    UILabel * titleLabel = [[UILabel alloc]init];
    titleLabel.font = kFont(14);
    titleLabel.textColor = HEX_RGB(0x8d919c);
    [view addSubview:titleLabel];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view);
        make.left.equalTo(view).offset(15);
    }];
    
    NSString * titleStr = self.ListHeader[section];
    
    titleLabel.text = titleStr;
    
    return view;
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //标题
    NSArray * titleArr = self.ListData[indexPath.section];
    NSString * titleStr = titleArr[indexPath.row];
    
    //占位字
    NSArray * placeHolderArr = self.ListPlaceHolder[indexPath.section];
    NSString * placeHolderStr = placeHolderArr[indexPath.row];
    
    //年龄城市、详细地址 过敏食物、过敏药物
    if (indexPath.section == 0 || indexPath.section == 4) {
        NSString * reuserId = [NSString stringWithFormat:@"KTiltleAndInputTableViewCell %li%li",(long)indexPath.section,(long)indexPath.row];
        KTiltleAndInputTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuserId];
        
        if (!cell) {
            cell = [[KTiltleAndInputTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserId];
        }
        cell.accessoryType = UITableViewCellAccessoryNone;

        cell.titleLabel.text = titleStr;
        cell.inputTextField.placeholder = placeHolderStr;
        cell.inputTextField.userInteractionEnabled = YES;
        if (indexPath.section == 0) {
            
            if (indexPath.row == 0) {
                self.phoneTextField = cell.inputTextField;
                self.phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
            }else if (indexPath.row == 1) {
                self.ageTextField = cell.inputTextField;
                self.ageTextField.keyboardType = UIKeyboardTypeNumberPad;
                self.ageTextField.delegate = self;

            }
          
        }else if (indexPath.section == 4){
            
            if (indexPath.row == 0) {
                self.medicinalTextField = cell.inputTextField;
            }else if(indexPath.row == 1){
                self.foodTextField = cell.inputTextField;
                
            }
        }
        
        return cell;
        //既往病史和生理状况
    }else if(indexPath.section == 1 || indexPath.section == 2){
        
        XMUserDetailInfoMultiSelectTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[XMUserDetailInfoMultiSelectTableViewCell className]];
        
        if (!cell) {
            cell = [[XMUserDetailInfoMultiSelectTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[XMUserDetailInfoMultiSelectTableViewCell className]];
        }
        
        if (indexPath.section == 1) {
            cell.tagList = self.tagListModel.medicalHistoryView;
        }else{
            cell.tagList = self.tagListModel.physiologicalConditionView;

        }
        
        return cell;
        
        //医美史
    }else if(indexPath.section == 3){
        
        //有医美史
        if (self.SurgeryDetailArr || self.createModel.partyRemark.length > 0) {
            
            XMSurgeryDetailTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[XMSurgeryDetailTableViewCell className]];
            
            if (!cell) {
                cell = [[XMSurgeryDetailTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[XMSurgeryDetailTableViewCell className]];
            }
            
            [cell.timeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(cell.contentView);
                make.height.equalTo(@0);
                
            }];
            
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.timeLabel.hidden = YES;
            cell.remarkTextView.userInteractionEnabled = NO;
            cell.remarkPlaceHolder.hidden = YES;
            cell.partLabel.text = @"部位:";
            cell.surgetyTypeLabel.text = @"项目位置:";
            cell.materialsLabel.text = @"材料:";
            cell.remarkTextView.text = self.createModel.partyRemark;
            //设置列表
            for (XMTypeListClassifyModel * thridModel in self.SurgeryDetailArr) {
                if (thridModel.isSelected) {
                    cell.partLabel.text = [NSString stringWithFormat:@"%@ %@",cell.partLabel.text,thridModel.name];
                }
                
                for (XMTypeListClassifyModel * fourthModel in thridModel.cateViews) {
                    if (fourthModel.isSelected) {
                        cell.surgetyTypeLabel.text = [NSString stringWithFormat:@"%@ %@",cell.surgetyTypeLabel.text,fourthModel.name];
                    }
                    
                    for (XMTypeListClassifyModel * fifthModel in fourthModel.cateViews) {
                        if (fifthModel.isSelected) {
                            cell.materialsLabel.text = [NSString stringWithFormat:@"%@ %@",cell.materialsLabel.text,fifthModel.name];
                        }
                    }
                }
            }
            return cell;
            
        }else{
            //无医美史
            KTiltleAndInputTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[KTiltleAndInputTableViewCell className]];
            
            if (!cell) {
                cell = [[KTiltleAndInputTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[KTiltleAndInputTableViewCell className]];
            }
            cell.inputTextField.text = @"";
            cell.titleLabel.text = titleStr;
            cell.inputTextField.placeholder = placeHolderStr;
            cell.inputTextField.userInteractionEnabled = NO;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            return cell;
            
            
        }

        //备注
    }else{
        XMRemarkTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:[XMRemarkTableViewCell className]];
        
        if (!cell) {
            cell = [[XMRemarkTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[XMRemarkTableViewCell className]];
        }
        
        cell.placeHolderLabel.text = @"请输入其他备注";
        self.remarkTextView = cell.remarkTextView;
        cell.remarkTextView.textColor = kTextGrayColor;
        cell.remarkTextView.text = self.createModel.extr;
        MJWeakSelf
        [cell setTextChangeBlock:^(NSString *text) {
            weakSelf.createModel.extr = text;
        }];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 3) {
        XMTypeListViewController * vc  = [[XMTypeListViewController alloc]init];
        vc.type = 2;
        MJWeakSelf
        [vc setCallbackBlock:^(NSArray *selectedItemList,NSString * extr) {
            
            weakSelf.SurgeryDetailArr = selectedItemList;
            weakSelf.createModel.partyRemark = extr;
            [weakSelf.tableView reloadSection:3 withRowAnimation:UITableViewRowAnimationNone];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark ----uitextFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSCharacterSet *cs;
    if(textField == self.ageTextField)
    {
        cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [string isEqualToString:filtered];
        if(!basicTest)
        {
            [KLProgressHUD showErrorHUDWithMessage:@"只能输入数字"];
            //输入了非法字符
            return NO;
        }
    }
    
    //其他的类型不需要检测，直接写入
    return YES;
}

#pragma mark ----getting&setting----
-(UIButton *)sureBtn{
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_sureBtn setBackgroundColor:kMainBlueColor];
        _sureBtn.titleLabel.font = kFont(14);
        [_sureBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        [_sureBtn addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_sureBtn];
    }
    return _sureBtn;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
